<template>
  <div class="system-notice-container">
    <h2 class="page-title">系统公告</h2>

    <!-- 顶部搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发布日期">
              <el-input
                  v-model="dateRangeText"
                  placeholder="请选择日期范围"
                  readonly
                  @click="showDatePickerDialog"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="关键字">
              <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入标题/内容/发布人/发布角色"
                  clearable
                  @keyup.enter="handleSearch"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="button-group">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
          <el-button type="success" @click="handleAdd" style="margin-left: 20px">
            <el-icon><Plus /></el-icon>
            新增公告
          </el-button>
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/announcement/upload"
              :on-success="handleFileSuccess"
              :limit="1"
          >
            <el-button type="primary" style="margin-left: 10px">批量上传</el-button>
          </el-upload>
        </el-row>
      </el-form>
    </el-card>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <el-table
          :data="paginatedData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="id" label="编号" min-width="50" />
        <el-table-column prop="messageTitle" label="消息标题" min-width="100" />
        <el-table-column prop="messageContent" label="消息内容" min-width="120" show-overflow-tooltip />
        <el-table-column prop="doctor.name" label="发布人" width="80" />
        <el-table-column prop="role.roleName" label="发布人角色" width="100" />
        <el-table-column prop="publishTime" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDateTimeForDisplay(scope.row.publishTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="80" >
          <template #default="scope">
            <span v-if="scope.row.status === 1">已发布</span>
            <span v-else>未发布</span> <!-- 或其他状态 -->
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" type="primary">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" @click="handleDelete(row)" type="danger">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日期选择器对话框 -->
    <el-dialog
        v-model="datePickerVisible"
        title="选择日期范围"
        width="700px"
        :close-on-click-modal="false"
    >
      <div class="date-picker-container">
        <div class="quick-select">
          <h4>快速选择</h4>
          <el-radio-group v-model="quickSelect" @change="handleQuickSelectChange">
            <el-radio-button label="week">最近一周</el-radio-button>
            <el-radio-button label="month">最近1个月</el-radio-button>
            <el-radio-button label="quarter">最近3个月</el-radio-button>
          </el-radio-group>
        </div>

        <div class="custom-range">
          <h4>自定义范围</h4>
          <div class="date-range-picker">
            <el-date-picker
                v-model="customDateRange[0]"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                @change="handleCustomDateChange"
            />
            <span class="separator">至</span>
            <el-date-picker
                v-model="customDateRange[1]"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="handleCustomDateChange"
            />
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="datePickerVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDateRange">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import router from "/src/router/index.js";
import axios from "axios";
import {formatDateTimeForDisplay} from "../../utils/dateUtil.js";

//批量上传
const handleFileSuccess = (
    resp,
    uploadFile
    //上传类操作，只用一个data，与图片相似；
) => {
  ElMessage.success(resp)
  //刷新数据
  fetchNoticeList();
};

// 搜索表单
const searchForm = reactive({
  startDate: '',
  endDate: '',
  keyword: ''
})


// 日期选择相关
const datePickerVisible = ref(false)
const quickSelect = ref('')
const customDateRange = ref(['', ''])
const dateRangeText = computed(() => {
  if (!searchForm.startDate || !searchForm.endDate) return ''
  return `${searchForm.startDate} 至 ${searchForm.endDate}`
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 公告列表数据
const noticeList = ref([
  {
    id: 1,
    messageTitle: '系统维护通知',
    messageContent: '系统将于2023-06-15凌晨2:00至5:00进行维护升级',
    doctorIdSend:null,
    roleId: null,
    publishTime: '2023-06-10 14:30:25',
    status: null,
    role:{id:null,roleName:''},
    doctor:{id:null,name:''}
  }
])

// 对话框相关
// 新增公告
const handleAdd = () => {
  router.push({
    path: "/newOrEditAnnouncement",
    query: {
      action: 'add'
    }
  })
}

// 编辑公告
const handleEdit = (row) => {
  router.push({
    path: "/newOrEditAnnouncement",
    query: {
      action: 'edit',
      id: row.id // 传递公告ID
    }
  })
}



// 表单验证规则
const rules = reactive({
  title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }]
})



// 显示日期选择器对话框
const showDatePickerDialog = () => {
  datePickerVisible.value = true
  quickSelect.value = ''
  customDateRange.value = [searchForm.startDate || '', searchForm.endDate || '']
}

// 快速选择日期范围
const handleQuickSelectChange = (val) => {
  const today = dayjs()
  let startDate = ''

  switch (val) {
    case 'week':
      startDate = today.subtract(1, 'week').format('YYYY-MM-DD')
      break
    case 'month':
      startDate = today.subtract(1, 'month').format('YYYY-MM-DD')
      break
    case 'quarter':
      startDate = today.subtract(3, 'month').format('YYYY-MM-DD')
      break
  }

  customDateRange.value = [startDate, today.format('YYYY-MM-DD')]
}

// 自定义日期变化
const handleCustomDateChange = () => {
  quickSelect.value = ''
}

// 确认日期范围
const confirmDateRange = () => {
  if (customDateRange.value[0] && customDateRange.value[1]) {
    searchForm.startDate = customDateRange.value[0]
    searchForm.endDate = customDateRange.value[1]
    datePickerVisible.value = false
  } else {
    ElMessage.warning('请选择完整的日期范围')
  }
}

// 搜索方法
const handleSearch = () => {
  pagination.currentPage = 1
  fetchNoticeList()
}

// 重置方法
const handleReset = () => {
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchForm.keyword = ''
  handleSearch()
}



// 删除公告修正
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除公告【${row.messageTitle}】吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/announcement/deleteAnnouncement/${row.id}`)
        .then(resp => {
          noticeList.value = noticeList.value.filter(item => item.id !== row.id)
          pagination.total = noticeList.value.length
          ElMessage.success(resp.data)
        })
        .catch(error => {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出数据
const handleExport = () => {
  loading.value = true
  // 模拟导出操作

  location.href="http://localhost:8080/announcement/download";
  setTimeout(() => {
    loading.value = false
    ElMessage.success('导出成功')
  }, 1000)
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchNoticeList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchNoticeList()
}

// 获取公告列表 (模拟)
// 计算当前页显示的数据
const paginatedData = computed(() => {
      const start = (pagination.currentPage - 1) * pagination.pageSize
      const end = start + pagination.pageSize
      return noticeList.value.slice(start, end)
    })


const fetchNoticeList = () => {
  loading.value = true
  axios.post(`/announcement/getAnnouncementList`,searchForm)
      .then(resp => {
        noticeList.value = resp.data
        pagination.total = noticeList.value.length
        loading.value = false
      })
      .catch(error => {
        console.error('获取公告列表失败:', error)
        loading.value = false
        ElMessage.error('获取公告列表失败')
      })
}
// 初始化数据
onMounted(() => {
  fetchNoticeList();

})



</script>

<style scoped>
.system-notice-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.date-picker-container {
  display: flex;
  gap: 30px;
}

.quick-select {
  flex: 1;
}

.custom-range {
  flex: 2;
}

.date-range-picker {
  display: flex;
  align-items: center;
  gap: 10px;
}

.separator {
  color: #606266;
  padding: 0 5px;
}

h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}
</style>